/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;
import TableModel.Hocphan;
import TableModel.Sinhvien;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.component.FileUpload;

/**
 *
 * @author vt
 */
public class ImportSinhVienHP {
    public  void uploadfile(FileUploadEvent event) {  
       (FileUpload) event.getComponent();
             String k  =  bind.getLabel();
             System.out.println("CHAY_______FILE " + k);
        ExternalContext extContext=FacesContext.getCurrentInstance().getExternalContext(); 
        File result = new File(extContext.getRealPath("//WEB-INF//files//" +event.getFile().getFileName() ));
        try {

            FileOutputStream fileOutputStream = new FileOutputStream(result);
            byte[] buffer = new byte[6124];
            int bulk;
            InputStream inputStream = event.getFile().getInputstream();  
             
           while (true) {
                 bulk = inputStream.read(buffer);
                  if (bulk < 0) {
                     break;
                 }
                fileOutputStream.write(buffer, 0, bulk);
                fileOutputStream.flush();
             }
        fileOutputStream.close();
       
         FileInputStream  fileInputStream = new FileInputStream(result);
          parserExcel(fileInputStream);
         System.out.println("File 13: "  + inputStream.available() + " " + inputStream.read());
       inputStream.close();
       fileInputStream.close();
           FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName()+ " is uploaded.");
              FacesContext.getCurrentInstance().addMessage(null, msg);
            } catch (IOException e) {
                        System.out.println ("Type not supported11111 :  " + e.toString());
                        FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "The files were not uploaded!", "");
                        FacesContext.getCurrentInstance().addMessage(null, error);

            }      
     }
     public boolean isShowUpload(){
      System.out.println("Show UPDOAD " + malop);
      if( lop != null && lop.getMahp() != null && !lop.getMahp().equals("")){
          return true;
      }else{
          return false;
      }
  }
     public long saveToDatabase(InputStream inputStream){
                POIFSFileSystem fileSystem = null;
    try
      {
                fileSystem = new POIFSFileSystem (inputStream);
                System.out.println(inputStream.available() + " " + inputStream.read());
                HSSFWorkbook      workBook = new HSSFWorkbook (fileSystem);
                HSSFSheet         sheet    = workBook.getSheetAt (0);
                Iterator rows     =  sheet.rowIterator ();
                  while (rows.hasNext ())
                     {
                          HSSFRow row = (HSSFRow) rows.next ();
                            // display row number in the console.
                        System.out.println ("Row No.: " + row.getRowNum ());
                              // once get a row its time to iterate through cells.
                          Iterator cells = row.cellIterator ();
                          while (cells.hasNext ())
                             {
                                    HSSFCell cell = (HSSFCell) cells.next ();
                                    System.out.println ("Cell No.: " + cell.getCellNum ());
                                    /*
                                     * Now we will get the cell type and display the values
                                     * accordingly.
                                     */
                switch (cell.getCellType ())
                {
                        case HSSFCell.CELL_TYPE_NUMERIC :
                        {
                                // cell type numeric.
                                System.out.println ("Numeric value: " + cell.getNumericCellValue ());

                                break;
                        }
                        case HSSFCell.CELL_TYPE_BLANK:
						System.out.println ("Cell Trong");
						break;
                        case HSSFCell.CELL_TYPE_STRING :
                        {
                                // cell type string.
                                HSSFRichTextString richTextString = cell.getRichStringCellValue ();
                                System.out.println ("String value: " + richTextString.getString ());

                                break;
                        }
                        default :
                        {
                                // types other than String and Numeric.
                                System.out.println ("Type not supported : ");
                                break;
                        }
                }
                }
                }
                }
                catch (IOException e)
                {
                    System.out.println ("Type not supported :  " + e.toString());
                   
                }
    return 0;
}
     public void parserExcel(FileInputStream f){
         WorkbookSettings ws = null;
         Workbook workbook  = null;
         Sheet s  = null;
         Cell rowData[] = null;
         int rowcount = 0;
         int columnCount  =0;
         int totalSheet  =0;
         try{
             ws = new WorkbookSettings();
             ws.setLocale(new Locale("vn","VN"));// 
             workbook  = Workbook.getWorkbook(f);
             // tong so sheet tren 1 file 
             totalSheet = workbook.getNumberOfSheets();
             if(totalSheet > 0){
                 System.out.println("Total Sheet found :" + totalSheet);
                 for(int i =0; i< totalSheet; ++i){
                     System.out.println("Sheet Name" + workbook.getSheet(i).getName());
                     
                 }
             }
             // doc thong tin sheet hien hanh 
             s = workbook.getSheet(0);
             // doc tieu de cua tung cot
             getHeadingOfXlsFile(s);
            String maLop  = updateTableLop(s);
             rowcount = s.getRows();
             System.out.println("Total Rows inside sheet: " + rowcount);
             columnCount  = s.getColumns();
             //Cell[] rowData1 = s.getRow(3);
              
             // System.out.println("Cell at 5  : " + rowData1[5].getContents());
             System.out.println("Total Col insinde Sheet: " + columnCount);
             for(int i = 10; i< rowcount; ++i){
                 rowData = s.getRow(i);
                System.out.println("Dong SO  ###   : " + i );
                 if(rowData.length >0){
                   //  if(&& rowData[0].getType() == CellType.NUMBER)
                            if(!rowData[0].getContents().equals("")  ){
                              Sinhvien   sv = new Sinhvien();
                                System.out.println("  " + rowData[0].getContents()  +  ": "        // so TT
                                                           +   "  "   +  rowData[1].getContents()  // MA SV
                                                           +   "  "   +  rowData[2].getContents()  // HO SV
                                                           +   "  "   +  rowData[3].getContents()  // TEN SV
                                                           +   "  "   +  rowData[4].getContents()  // TEN SV
                                                    );
                                  sv.setMasv(rowData[1].getContents() );
                                  sv.setHosv(rowData[2].getContents());
                                  sv.setTensv(rowData[3].getContents());
                              
                                  System.out.println("Total Col insinde Sheet: " + sv.toString());
                                svBo.add(sv);
                            }
                           System.out.println();
                        
                      }
                 
             }
             workbook.close();
         }catch(Exception e){
             System.out.println("Error at Read File Excel :" + e.toString());
         }
     }
     public void getHeadingOfXlsFile(Sheet s){
         int colCount  = s.getColumns();
         for(int i =0; i< colCount; ++i){
             System.out.println(s.getCell(i,0).getContents());
         }
     }
     public String updateTableLop(Sheet s){
           String result ="";
             Hocphan lop1 = new Hocphan();
             lop1.setMagv("");
             lop1.setMahk("");
             lop1.setMamh("");
            
             
             Cell[] rowData = s.getRow(3); // row show ma lop1
            if(rowData.length >0){
                 result = rowData[5].getContents();
             lop1.setMahp(rowData[5].getContents()); 
            }
          rowData = s.getRow(2); // row show ma lop1
          if(rowData.length >0){
             lop1.setTenhp(rowData[5].getContents()); 
          }
          if(!result.equals("")){
             Hocphan  l = hpBO.findById(result);
              if(l!= null){
                  
              }else {
                   hpBO.add(lop1);
              }   
          }
         
         
          return result;
     }
}
